import { useEffect, useRef } from "react";

/**
 * 自定义hook节流
 * @param callback 回调函数
 * @param delay 时间(毫秒)
 * @param isLastEvent 最后一次事件是否执行？默认false
 * @returns
 */
export const useThrottle = (
  callback: Function,
  delay: number,
  isLastEvent: boolean = false
) => {
  const timeoutRef = useRef<number | null>(null);
  const lastExecTimeRef = useRef<number>(0);

  useEffect(() => {
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, []);

  const throttledCallback = (...args: any[]) => {
    const currentTime = Date.now();
    const remainingTime = delay - (currentTime - lastExecTimeRef.current);

    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }

    if (remainingTime <= 0) {
      callback(...args);
      lastExecTimeRef.current = currentTime;
    } else if (isLastEvent) {
      timeoutRef.current = setTimeout(() => {
        callback(...args);
        lastExecTimeRef.current = Date.now();
      }, remainingTime);
    }
  };

  return throttledCallback;
};
